package com.dongwq.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class TextUtil {
	private final static Pattern url_pattern = Pattern.compile("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?");

	/**
	 * 自动为文本中的url生成链接
	 * 
	 * @param txt
	 * @param only_oschina
	 * @return
	 */
	public static String autoMakeLink(String txt, boolean only_oschina) {
		StringBuilder html = new StringBuilder();
		int lastIdx = 0;
		Matcher matchr = url_pattern.matcher(txt);
		while (matchr.find()) {
			String str = matchr.group();
			html.append(txt.substring(lastIdx, matchr.start()));
			if (!only_oschina || StringUtils.containsIgnoreCase(str, "oschina.net"))
				html.append("<a href='" + str + "'>" + str + "</a>");
			else
				html.append(str);
			lastIdx = matchr.end();
		}
		html.append(txt.substring(lastIdx));
		return html.toString();
	}
}
